import React, { useState, useRef, useEffect } from 'react'
import './message.css'

interface Message {
  id: string
  text: string
  sender: 'user' | 'other'
  timestamp: Date
  isAI?: boolean
}

interface Doctor {
  id: number
  name: string
  title: string
  hospital: string
  specialty: string
}

interface WebSocketMessage {
  type: string
  id?: string
  text?: string
  sender?: 'user' | 'other'
  timestamp?: string
  status?: string
  message?: string
}

function Index() {
  const [messages, setMessages] = useState<Message[]>([])
  const [inputText, setInputText] = useState('')
  const [selectedDoctor, setSelectedDoctor] = useState<Doctor | null>(null)
  const [isConnected, setIsConnected] = useState(false)
  const [isTyping, setIsTyping] = useState(false)
  const [connectionStatus, setConnectionStatus] = useState<'connecting' | 'connected' | 'disconnected'>('disconnected')
  
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const wsRef = useRef<WebSocket | null>(null)
  const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null)

  // 获取选中的医生信息
  useEffect(() => {
    const doctorData = localStorage.getItem('selectedDoctor')
    if (doctorData) {
      try {
        const doctor = JSON.parse(doctorData)
        setSelectedDoctor(doctor)
        // 保存为最后聊天的医生
        localStorage.setItem('lastChatDoctor', doctorData)
        // 添加欢迎消息
        setMessages([
          {
            id: '1',
            text: `您好！我是${doctor.name}医生，${doctor.title}，来自${doctor.hospital}。有什么可以帮助您的吗？`,
            sender: 'other',
            timestamp: new Date()
          }
        ])
      } catch (error) {
        console.error('解析医生信息失败:', error)
        // 默认消息
        setMessages([
          {
            id: '1',
            text: '你好！我是小维AI助手，有什么可以帮助你的吗？',
            sender: 'other',
            timestamp: new Date(),
            isAI: true
          }
        ])
      }
    } else {
      // 默认消息
              setMessages([
          {
            id: '1',
            text: '你好！我是小维AI助手，有什么可以帮助你的吗？',
            sender: 'other',
            timestamp: new Date(),
            isAI: true
          }
        ])
    }
  }, [])

  // WebSocket连接管理
  useEffect(() => {
    connectWebSocket()
    
    return () => {
      if (wsRef.current) {
        wsRef.current.close()
      }
      if (reconnectTimeoutRef.current) {
        clearTimeout(reconnectTimeoutRef.current)
      }
    }
  }, [])

  const connectWebSocket = () => {
    setConnectionStatus('connecting')
    
    try {
      const ws = new WebSocket('ws://localhost:8000')
      wsRef.current = ws

      ws.onopen = () => {
        console.log('WebSocket连接成功')
        setIsConnected(true)
        setConnectionStatus('connected')
        setMessages(prev => [...prev, {
          id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
          text: '✅ 已连接到AI助手',
          sender: 'other',
          timestamp: new Date(),
          isAI: true
        }])
      }

      ws.onmessage = (event) => {
        try {
          const data: WebSocketMessage = JSON.parse(event.data)
          console.log('收到WebSocket消息:', data)
          
          switch (data.type) {
            case 'status':
              if (data.status === 'connected') {
                setIsConnected(true)
                setConnectionStatus('connected')
              }
              break
            case 'message':
              if (data.text && data.id) {
                const newMessage: Message = {
                  id: data.id,
                  text: data.text,
                  sender: data.sender || 'other',
                  timestamp: data.timestamp ? new Date(data.timestamp) : new Date(),
                  isAI: true
                }
                setMessages(prev => [...prev, newMessage])
              }
              break
            default:
              console.log('未知消息类型:', data.type)
          }
        } catch (error) {
          console.error('解析WebSocket消息失败:', error)
        }
      }

      ws.onclose = () => {
        console.log('WebSocket连接关闭')
        setIsConnected(false)
        setConnectionStatus('disconnected')
        
        // 自动重连
        if (reconnectTimeoutRef.current) {
          clearTimeout(reconnectTimeoutRef.current)
        }
        reconnectTimeoutRef.current = setTimeout(() => {
          console.log('尝试重新连接...')
          connectWebSocket()
        }, 3000)
      }

      ws.onerror = (error) => {
        console.error('WebSocket连接错误:', error)
        setIsConnected(false)
        setConnectionStatus('disconnected')
      }
    } catch (error) {
      console.error('创建WebSocket连接失败:', error)
      setConnectionStatus('disconnected')
    }
  }

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  useEffect(() => {
    scrollToBottom()
  }, [messages])

  const handleSendMessage = () => {
    if (inputText.trim() && wsRef.current && isConnected) {
      const messageId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
      
      // 添加用户消息到界面
      const newMessage: Message = {
        id: messageId,
        text: inputText,
        sender: 'user',
        timestamp: new Date()
      }
      setMessages(prev => [...prev, newMessage])
      
      // 发送消息到WebSocket服务器
      wsRef.current.send(JSON.stringify({
        type: 'message',
        content: inputText,
        timestamp: new Date().toISOString()
      }))
      
      setInputText('')
      setIsTyping(false)
    } else if (!isConnected) {
      // 如果未连接，显示连接提示
      setMessages(prev => [...prev, {
        id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
        text: '❌ 连接已断开，正在尝试重新连接...',
        sender: 'other',
        timestamp: new Date(),
        isAI: true
      }])
    }
  }

/**
 * 处理键盘事件的函数
 * @param e - React键盘事件对象，包含键盘事件的详细信息
 */
/**
 * 处理键盘事件的处理函数
 * @param {React.KeyboardEvent} e - 键盘事件对象
 */
  const handleKeyPress = (e: React.KeyboardEvent) => {
  // 判断是否按下了Enter键且没有按下Shift键
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSendMessage()
    }
  }

  const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setInputText(e.target.value)
    
    // 发送输入状态
    if (wsRef.current && isConnected) {
      wsRef.current.send(JSON.stringify({
        type: 'typing',
        isTyping: e.target.value.length > 0
      }))
      setIsTyping(e.target.value.length > 0)
    }
  }

  const formatTime = (date: Date) => {
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }

  const getConnectionStatusText = () => {
    switch (connectionStatus) {
      case 'connecting':
        return '🔄 连接中...'
      case 'connected':
        return '✅ 已连接'
      case 'disconnected':
        return '❌ 未连接'
      default:
        return '❓ 未知状态'
    }
  }

  return (
    <div className="chat-container">
      {/* 聊天头部 */}
      <div className="chat-header">
        <div className="chat-header-left">
          <button className="back-btn" onClick={() => window.history.back()}>
            <i className="back-icon">←</i>
          </button>
          <div className="chat-header-info">
            <div className="user-info">
              <h3>{selectedDoctor ? `${selectedDoctor.name}医生` : '小维AI助手'}</h3>
              <span className={`status ${isConnected ? 'online' : 'offline'}`}>
                {getConnectionStatusText()}
              </span>
              {selectedDoctor && (
                <span className="doctor-title">{selectedDoctor.title} | {selectedDoctor.hospital}</span>
              )}
            </div>
          </div>
        </div>
        <div className="chat-actions">
          <button 
            className="action-btn"
            onClick={connectWebSocket}
            title="重新连接"
          >
            <i className="icon">🔄</i>
          </button>
          <button className="action-btn">
            <i className="icon">📞</i>
          </button>
          <button className="action-btn">
            <i className="icon">📹</i>
          </button>
          <button className="action-btn">
            <i className="icon">⋯</i>
          </button>
        </div>
      </div>

      {/* 消息列表 */}
      <div className="messages-container">
        <div className="messages-list">
          {messages.map((message) => (
            <div
              key={message.id}
              className={`message ${message.sender === 'user' ? 'message-user' : 'message-other'}`}
            >
              <div className="message-content">
                <div className="message-bubble">
                  {message.text}
                  {message.isAI && (
                    <div className="ai-badge">AI</div>
                  )}
                </div>
                <div className="message-time">
                  {formatTime(message.timestamp)}
                </div>
              </div>
            </div>
          ))}
          {isTyping && (
            <div className="message message-other">
              <div className="message-content">
                <div className="message-bubble typing-indicator">
                  <span className="typing-dot"></span>
                  <span className="typing-dot"></span>
                  <span className="typing-dot"></span>
                </div>
              </div>
            </div>
          )}
          <div ref={messagesEndRef} />
        </div>
      </div>

      {/* 输入区域 */}
      <div className="input-container">
        <div className="input-wrapper">
          <textarea
            value={inputText}
            onChange={handleInputChange}
            onKeyPress={handleKeyPress}
            placeholder={isConnected ? "输入消息..." : "连接中，请稍候..."}
            className="message-input"
            rows={1}
            disabled={!isConnected}
          />
          <button
            onClick={handleSendMessage}
            className="send-button"
            disabled={!inputText.trim() || !isConnected}
          >
            <i className="send-icon">📤</i>
          </button>
        </div>
        <div className="input-actions">
          <button className="action-btn" disabled={!isConnected}>
            <i className="icon">📎</i>
          </button>
          <button className="action-btn" disabled={!isConnected}>
            <i className="icon">😊</i>
          </button>
          <button className="action-btn" disabled={!isConnected}>
            <i className="icon">📷</i>
          </button>
        </div>
      </div>
    </div>
  )
}

export default Index